﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2009, 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.MobileControls;
using System.Web.UI.WebControls;

using NHibernate.Criterion;

using Twipler.Data.Access;
using Twipler.Data.Entity.Twipler;

using Twipler.App;
using Twipler.WebApp;

using Twipler.Xtensions;


namespace Settings.Admin
{
    [RequireUser(VisitorRole.SuperAdmin)]
    public partial class ListUsers : Page
    {

        private Dictionary<int, string[]> ColumnMap = new Dictionary<int, string[]>()
                                                          {
                                                              {0, null},
                                                              {1, new string[] { "ScreenName", "Screen name" }},
                                                              {2, new string[] { "Name", "Name" }},
                                                              {3, new string[] { "Role", "Role" }},
                                                              {4, new string[] { "Design", "Design" }},
                                                              {5, new string[] { "LoginCount", "Login count" }},
                                                              {6, new string[] { "LastLogin", "Last twipler login" }}
                                                          };
        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                UpdateDisplay();
        }

        protected void editUser_Update()
        {
            UpdateDisplay();
        }

        private void UpdateDisplay()
        {
            string orderBy = Request.QueryStringString("OrderBy", string.Empty);
            
            List<Visitor> list;
            List<ICriterion> filter = GetFilterCriteria();
         
            if (string.IsNullOrEmpty(orderBy))
            {
                list = Factory.Visitor.GetByCriteria(filter.ToArray());
                listPaging.UpdateDisplay("ListUsers.aspx?", list.Count);
            }
            else
            {
                bool ascending = Request.QueryStringBool("asc", false);
                list = Factory.Visitor.GetByCriteria(orderBy, ascending, filter);
                listPaging.UpdateDisplay(string.Format("ListUsers.aspx?OrderBy={0}&Asc={1}&", orderBy, ascending ? "t" : "f"), list.Count);
            }            

            grdUsers.DataSource = list.Skip(listPaging.StartIndex).Take(Current.ResultsPerPage);
            grdUsers.DataBind();        
        }

        protected void grdUser_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            int userId = int.Parse(e.Item.Cells[0].Text);

            switch (e.CommandName)
            {
                case "Edit":
                    editUser.Entity = Factory.Visitor.GetById(userId, false);
                    editUser.UpdateDisplay();
                    mpeThePopup.Show();
                    break;
            }
        }

        protected void grdUsers_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            string orderBy = Request.QueryStringString("orderby", null);
            bool ascending = Request.QueryStringBool("asc", true);

            if (e.Item.ItemType == ListItemType.Header)
            {
                foreach (KeyValuePair<int, string[]> item in ColumnMap)
                {
                    if (item.Value == null)
                        continue;

                    string[] settings = (string[])item.Value;
                    string headerName = settings[1];

                    if (settings[0] == orderBy)
                        headerName += ascending ? " <b>^</b>" : " <b>v</b>";

                    headerName = "<a href=\"ListUsers.aspx?Page=" + listPaging.StartIndex / Current.ResultsPerPage + "&OrderBy=" + settings[0] + "&asc=" + (ascending ? "f" : "t") + " \">" + headerName + "</a>";

                    e.Item.Cells[item.Key].Text = headerName;
                }
            }

        }

        protected void listPaging_Changed()
        {
            UpdateDisplay();
        }

        protected void btnFilterOpt_Click(object sender, EventArgs e)
        {
            drpRoles.DataSource = Enum.GetNames(typeof(VisitorRole));
            drpRoles.DataBind();
            drpRoles.Items.Insert(0, new ListItem("All", ""));

            drpTheme.DataSource = Factory.Design.GetAll();
            drpTheme.DataTextField = "Name";
            drpTheme.DataValueField = "Id";
            drpTheme.DataBind();
            drpTheme.Items.Insert(0, new ListItem("All", ""));

            mpeFilterOpts.Show();
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            UpdateDisplay();
        }

        private List<ICriterion> GetFilterCriteria()
        {
            List<ICriterion> criterion = new List<ICriterion>();

            if (!String.IsNullOrEmpty(txtNameLike.Text.Trim()))
            {
                criterion.Add(Expression.Like("ScreenName", "%" + txtNameLike.Text + "%"));
            }

            if (drpRoles.SelectedValue != "")
                criterion.Add(Expression.Eq("Role", (int)Enum.Parse(typeof(VisitorRole), drpRoles.SelectedValue)));

            if (drpTheme.SelectedValue != "")
                criterion.Add(Expression.Eq("Design", Factory.Design.GetById(int.Parse(drpTheme.SelectedValue), false)));

            return criterion;
        }
    }
}